#include "Thread.hpp"
#include <vector>

#define NUM 4
using namespace ThreadModule;

//锁本身是全局的，也是共享资源。
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticketnum = 10000;

class ThreadData
{
public:
    std::string name;
    pthread_mutex_t *lock_ptr;
};

void Ticket(ThreadData &td)
{
    while (true)
    {
        pthread_mutex_lock(td.lock_ptr);//加锁
        if (ticketnum > 0)
        {
            usleep(1000);//休眠1毫秒
            //1.抢票
            std::cout << "get a new ticket, id: " << ticketnum-- << ", who get it: " << td.name << std::endl;

            pthread_mutex_unlock(td.lock_ptr);//解锁
            
            //2.入库
            usleep(1000);
        }
        else
        {
            pthread_mutex_unlock(td.lock_ptr);//解锁
            break;
        }
    }
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);//局部锁需要init初始化

    std::vector<Thread<ThreadData>> threads;
    for (int i = 0; i < NUM; i++)
    {
        ThreadData *td = new ThreadData();
        td->lock_ptr = &lock;
        threads.emplace_back(Ticket, *td);
        td->name = threads.back().Name();
    }

    for (auto &thread : threads)
    {
        thread.Start();
    }

    for (auto &thread : threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&lock);//局部锁需要手动释放
    return 0;
}
